<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Shopcar;
use DB,Session;

class ShopcarController extends CommonController
{   
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //获取购物车中的商品信息
        $data = Shopcar::getCartList();
        return view('home.goods.shopcar', compact("data"));
    }
    
    // 商品详情页加入购物车
    public function addCar(Request $request)
    {
        // 验证是否登录
        if(!$this->isLogin()){
            return response()->json(['status'=>-1, 'info'=>'请先登录']);
        }
        
        $data = $request->except('_token');
        $res = Shopcar::addCart($data);
        
        if(false !== $res){
            return response()->json(['status'=>1, 'info'=>'加入购物车成功']);
        } else {
            return response()->json(['status'=>0, 'info'=>'加入购物车失败']);
        }
    }
    
    //商品移除购物车
    public function deleteCar (Request $request, $id=0)
    {
        $id = $id ? $id : $request->get('id');
        //获取商品信息
        $res = Shopcar::where("id", $id)->delete();
        if($request->ajax()){
            if(false != $res){
                return response()->json(['status'=>1, 'info'=>'删除成功']);
            } else {
                return response()->json(['status'=>0, 'info'=>'删除失败']);
            }
        }
        return back();
    }
    
    //ajax修改购物车页面的商品数量
    public function updateCar(Request $request)
    {
        $data = $request->all();
        $res = Shopcar::changeNum($data);
        //返回修改信息
        if(false !== $res){
            return response()->json(['status'=>1, 'info'=>'修改商品数量成功']);
        } else {
            return response()->json(['status'=>0, 'info'=>'修改商品数量失败']);
        }
    }
    
    // ajax获取购物车数量
    public function getCartNum()
    {
        $res = Shopcar::getCartList();
        if(false != $res){
            return response()->json(['status'=>1, 'info'=>$res]);
        } else {
            return response()->json(['status'=>0, 'info'=>'购物车空空如也']);
        }
    }
    
    public function cartCount()
    {
        
    }
}